﻿//  <script src="http://webapi.amap.com/maps?v=1.3&key=@(Configs.GetValue("AMAP_JS_API_KEY"))&plugin=AMap.PolyEditor,AMap.CircleEditor"></script>
//  <script src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
//  <script src="~/Content/js/amap/amap-edit-line.js"></script>
//  $("#locMap").editLine({
//      locInputId: "F_Locations",
//      title: $("#F_StopName").val()
//  });
(function () {
    $.fn.editLine = function (options) {
        var defaultOptions = {
            locInputId: undefined,
            zoom: 13 //地图显示的缩放级别
        };
        var opts = $.extend(defaultOptions, options);
        var $this = $(this);
        var locStr = $("#" + opts.locInputId).val();
        var locJson = JSON.parse(locStr);
        if (locJson == null) {
            $this.html("初始数据不存在或格式错误，无法编辑");
            return;
        }
        var locPoints = locJson.LocPoints;
        var lineArr = [];//线路所有点集合
        var stopArr = [];//不可编辑点集合
        var stopPositionArr = [];//不可编辑点title
        for (var i = 0; i < locPoints.length; i++) {
            var lp = locPoints[i];
            lineArr.push([lp.Lng, lp.Lat]);
            if (lp.IsStop) {
                stopArr.push([lp.Lng, lp.Lat]);
                stopPositionArr.push(lp.Position);
            }
        }

        //在地图上绘制折线
        var map = new AMap.Map($this.attr("id"), {
            resizeEnable: true,
            zoom: 13 //地图显示的缩放级别
        });
        var editor = {};
        editor._line = (function () {
            return new AMap.Polyline({
                map: map,
                path: lineArr,
                strokeColor: "#FF33FF",//线颜色
                strokeOpacity: 1,//线透明度
                strokeWeight: 3,//线宽
                strokeStyle: "solid"//线样式
            });
        })();
        lineArr = getArryFromPath(editor._line.getPath());

        //初始化上传控件
        function init() {

            map.setFitView();
            editor._lineEditor = new AMap.PolyEditor(map, editor._line);

            editor.startEditLine = function () {
                editor._lineEditor.open();
            }
            editor.closeEditLine = function () {
                editor._lineEditor.close();
            }
            //editor._lineEditor.open();

            //标注不可编辑点
            for (var i = 0; i < stopArr.length; i++) {
                var marker = new AMap.Marker({
                    icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                    position: stopArr[i],
                    title: stopPositionArr[i] + ""
                });
                marker.setMap(map);
            }

            //增加点
            editor._lineEditor.on("addnode", function (e) {
                var mp = [e.lnglat.lng, e.lnglat.lat];
                updateLocation(1, mp);
            });

            //移动点
            editor._lineEditor.on("adjust", function (e) {
                var path = editor._line.getPath();
                var pathP = getArryFromPath(path);
                var mps = getMovedPoint(lineArr, pathP);
                var isStop = isPointInArray(mps[0], stopArr);
                if (isStop) {
                    editor._line.setPath(lineArr);
                    lineArr = getArryFromPath(editor._line.getPath());
                    return;
                }
                updateLocation(2, mps[0], mps[1]);
            });

            //删除点
            editor._lineEditor.on("removenode", function (e) {
                var mp = [e.lnglat.lng, e.lnglat.lat];
                var isStop = isPointInArray(mp, stopArr);
                if (isStop) {
                    setTimeout(function () {
                        editor._line.setPath(lineArr);
                        lineArr = getArryFromPath(editor._line.getPath());
                    }, 100);
                    return;
                }
                updateLocation(3, mp);
            });


            var html = '' +
'            <div class="button-group">' +
'                <input id="beginEditLien" type="button" class="button" value="开始编辑折线" />' +
'                <input id="endEditLien" type="button" class="button" value="结束编辑折线" />' +
'            </div>';
            $this.parent().append(html);
            $("#beginEditLien").click(function () {
                editor.startEditLine();
            });
            $("#endEditLien").click(function () {
                editor.closeEditLine();
            });
        }
        //运行初始化
        init();

        //修改路径
        function updateLocation(type, p1, p2) {
            if (type == 1) {//新增
                var path = editor._line.getPath();
                var pathP = getArryFromPath(path);
                for (var i = 0; i < pathP.length; i++) {
                    if (checkPosition(pathP[i], p1)) {
                        locPoints.splice(i, 0, {
                            Lng: p1[0],
                            Lat: p1[1],
                            IsStop: false,
                            Position: 0
                        });
                        break;
                    }
                }
            } else if (type == 2) {//移动
                for (var i = 0; i < locPoints.length; i++) {
                    var lp = locPoints[i];
                    if (checkPosition([lp.Lng, lp.Lat], p1)) {
                        lp.Lng = p2[0];
                        lp.Lat = p2[1];
                        break;
                    }
                }
            } else if (type == 3) {//删除 splice
                for (var i = 0; i < locPoints.length; i++) {
                    var lp = locPoints[i];
                    if (checkPosition([lp.Lng, lp.Lat], p1)) {
                        locPoints.splice(i, 1);
                        break;
                    }
                }
            }
            var pathP = getArryFromPath(editor._line.getPath());
            lineArr = pathP;
            $("#" + opts.locInputId).val(JSON.stringify(locJson));
        }

        //根据ampa的path获取位置数组
        function getArryFromPath(path) {
            var list = [];
            for (var i = 0; i < path.length; i++) {
                var p = path[i];
                var p1 = [p.lng, p.lat];
                list.push(p1);
            }
            return list;
        }

        //比较两个位置数组，找到移动了位置
        function getMovedPoint(oldArry, arry) {
            for (var i = 0; i < arry.length; i++) {
                var p = arry[i];
                var oldP = oldArry[i];
                if (!checkPosition(p, oldP)) {
                    return [oldP, p];
                }
            }
            return null;
        }

        //判断两个位置是否相同
        function checkPosition(p1, p2) {
            return p1[0] == p2[0] && p1[1] == p2[1];
        }

        //判断点p是否在arry中
        function isPointInArray(p, arry) {
            for (var i = 0; i < arry.length; i++) {
                var ap = arry[i];
                if (checkPosition(p, ap)) {
                    return true;
                }
            }
            return false;
        }

    };
})(jQuery);
